package com.lyhcc.utils;

public class Calculator {
    public static Fraction cal(Fraction a,Fraction b ,char op){
        Fraction answer = null;



        switch (op){
            case  '+':
                fractionToCommon(a,b);
                answer = new Fraction(a.getMolecular()+b.getMolecular() , a.getDenominator());
                break;
            case  '-':
                fractionToCommon(a,b);

                answer = new Fraction(a.getMolecular()-b.getMolecular() , a.getDenominator());
                break;
            case  '×':
                answer = multi(a,b);
                break;
            case  '÷':
                /*
                分数除法，除数分子分母互换位置后相乘
                 */
                b.swap();
                answer = multi(a,b);
                break;

        }
        fractionToSimple(answer);
        return answer;
    }

    private static Fraction multi(Fraction a, Fraction b){
        return new Fraction(a.getMolecular()*b.getMolecular() , a.getDenominator()*b.getDenominator());
    }

    public static void fractionToCommon(Fraction a ,Fraction b){
        int denominator_a = a.getDenominator();
        int denominator_b = b.getDenominator();

        int gcd = GCD(denominator_a,denominator_b);
        int lcm = LCM(gcd,denominator_a*denominator_b);

        a.setMolecular(lcm/denominator_a*a.getMolecular());
        a.setDenominator(lcm);
        b.setMolecular(lcm/denominator_b*b.getMolecular());
        b.setDenominator(lcm);

    }
    public static void fractionToSimple(Fraction a){
        int molecular = a.getMolecular();
        int denominator = a.getDenominator();

        int gcd = GCD(molecular,denominator);

        a.setDenominator(denominator/gcd);
        a.setMolecular(molecular/gcd);

    }
    /**
     *用于计算最大公约数
     * @param m 整数1
     * @param n 整数2
     * @return m和n的最大公约数
     */
    private static int GCD(int m,int n){
        int r = 0;
        while(n != 0){
            r= m%n;
            m = n;
            n = r;
        }
        return m;

    }

    /**
     *  用于计算最小公倍数
     * @param gcd m和n的最大公约数
     * @param mn   m*n
     * @return m和n的最小公倍数
     */
    private static int LCM(int gcd,int mn){
        return mn/gcd;
    }
}
